
package com.kweative.lingua.server.protocol;

import com.kweative.format.UrlFormat;
import com.kweative.lingua.server.structures.AppRequest;
import com.kweative.lingua.server.exceptions.NotFoundException;
import com.kweative.lingua.server.request.RequestHandler;
import com.kweative.lingua.server.structures.ArgumentsNamed;
import com.kweative.network.HttpRequest;
import com.kweative.type.Node;
import java.net.URL;

/**
 *
 * @author henrik
 */

public class UrlProtocol extends XmlSimpleProtocol {

    public UrlProtocol() {
        reserved = new String[]{"output"};
    }

    @Override
    public boolean canRead(RequestHandler request) {
        if (request.getFormat() instanceof UrlFormat && request instanceof HttpRequest) {
            return true;
        }
        return false;
    }
    @Override
    public AppRequest[] read(RequestHandler request) throws NotFoundException {
        AppRequest r = new AppRequest();
        Node d = request.getData();

        URL url = ((HttpRequest)request).getUrl();
        String parts[] = url.getPath().split("/");
        if (parts.length == 4) {
            r.setSID(((HttpRequest) request).getCookie(getSessionIdName()));
            r.setApplicationName(parts[1]);
            r.setControllerName(parts[2]);
            r.setMethodName(parts[3]);
        } else
            throw new NotFoundException("Invalid path: Correct syntax /appname/controller/method/!");
        
        ArgumentsNamed arguments = new ArgumentsNamed();
        if (d != null && d.hasChildren()) {
            for(Node child:d.children()) {
                if (!isReserved(child.getName(),request.getResponseProtocol())) {
                    arguments.add(child.getName(),child);
                }
            }
        }
        r.setArguments(arguments);
        
        return new AppRequest[]{r};
    }

    @Override
    public Protocol getDefaultResponse() {
        return new XmlSimpleProtocol();
    }

}
